package com.company.sendemo.basics.akJavaString.regularexpression;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class expression2 {
    /**
     * matches 和 lookingAt 方法都用来尝试匹配一个输入序列模式。它们的不同是 matches 要求整个序列都匹配，而lookingAt 不要求。
     * lookingAt 方法虽然不需要整句都匹配，但是需要从第一个字符开始匹配。
     * 这两个方法经常在输入字符串的开始使用。
     */
    private static final String REGEX = "foo";
    private static final String INPUT = "fooooooooooooooooo";
    private static final String INPUT2 = "ooooofoooooooooooo";
    private static Pattern pattern;
    private static Matcher matcher;
    private static Matcher matcher2;


    /**
     * replaceFirst 和 replaceAll 方法用来替换匹配正则表达式的文本。不同的是，replaceFirst 替换首次匹配，replaceAll 替换所有匹配
     */
    private static String REGEX3 = "dog";
    private static String INPUT3 = "The dog says meow. " +
            "All dogs say meow.";
    private static String REPLACE3 = "cat";

    /**
     * Matcher 类也提供了appendReplacement 和 appendTail 方法用于文本替换
     * @param args
     */
    private static String REGEX4 = "a*b";
    private static String INPUT4 = "aabfooaabfooabfoobkkk";
    private static String REPLACE4 = "-";

    public static void main( String[] args ){
        pattern = Pattern.compile(REGEX);
        matcher = pattern.matcher(INPUT);
        matcher2 = pattern.matcher(INPUT2);

        System.out.println("Current REGEX is: "+REGEX);
        System.out.println("Current INPUT is: "+INPUT);
        System.out.println("Current INPUT2 is: "+INPUT2);


        System.out.println("lookingAt(): "+matcher.lookingAt());
        System.out.println("matches(): "+matcher.matches());
        System.out.println("lookingAt(): "+matcher2.lookingAt());


        Pattern compile = Pattern.compile(REGEX3);
        Matcher matcher = compile.matcher(INPUT3);
        String s = matcher.replaceFirst(REPLACE3);
        String s1 = matcher.replaceAll(REPLACE3);
        System.out.println("replaceFirst   :"+s);
        System.out.println("replaceAll     :"+s1);


        Pattern compile1 = Pattern.compile(REGEX4);
        Matcher matcher1 = compile1.matcher(INPUT4);
        StringBuffer stringBuffer = new StringBuffer();
        while (matcher1.find()){
            matcher1.appendReplacement(stringBuffer,REPLACE4);
        }
        matcher1.appendTail(stringBuffer);
        System.out.println(stringBuffer.toString());


    }
}
